<template>
  <view class="container" :style="containerStyle">
    <!-- #ifdef APP-PLUS   -->
    <web-view :webview-styles="webviewStyles" src="http://121.229.177.46:89"  @message="handleWebViewMessage"></web-view>
    <!-- #endif   -->

    <!-- #ifdef H5 -->
    <web-view :webview-styles="webviewStyles" src="http://121.229.177.46:89" @message="handleWebViewMessage"></web-view>
    <!-- #endif   -->
  </view>
</template>

<script>
import { useUserStore } from "@/pinia-store/user.js";
import { mapStores } from 'pinia';
export default {
  name: 'parkHome',
  data () {
    return {
      wv: null,
      webviewStyles: {
        progress: {
          color: '#67b5f0'
        },
      },
      backgroundColor: '#ffffff',
      token: null,
    }
  },
  computed: {
    containerStyle () {
      if (this.backgroundColor === '#15a096') {
        return { backgroundColor: this.backgroundColor };
      } else {
        return { backgroundImage: this.backgroundColor };
      }
    },
    ...mapStores(useUserStore),
  },
  onLoad () {
    // #ifdef APP-PLUS
    const currentWebview = this.$scope.$getAppWebview();
    const screenHeight = uni.getSystemInfoSync().screenHeight;
    const topPx = screenHeight * 0.03;

    this.waitForWebviewChildWithRetry(currentWebview, (wv) => {
      wv.setStyle({
        top: `${topPx}px`,
        height: `${screenHeight - topPx}px`,
        width: '100%'
      });

      wv.onloaded = () => {
        this.sendAppInitMessageToWebView();
      };

      this.wv = wv;
    });
    // #endif
  },
  onUnload () {
    this.sendMessageToWebViewBeforeDestroy(); // 页面销毁前发送消息
    // #ifdef APP-PLUS
    if (this.wv) {
      this.wv.removeFromParent(true); // 从父容器中移除
      this.wv = null; // 销毁 webview 引用
    }
    // #endif

    // #ifdef H5
    window.removeEventListener('message', this.handleVueToUniAppMessage);
    // #endif
  },
  mounted () {
    this.token = this.userStore.user.token
    // #ifdef H5
    // h5端 uni-app -> vue 发送消息
    this.$nextTick(() => {
      const iframe = document.querySelector('iframe');
      if (iframe) {
        iframe.onload = () => {
          if (iframe && iframe.contentWindow) {
            iframe.contentWindow.postMessage({ type: 'uniAppToVueMessage',payload: 'web',message:{
                token:this.userStore.user.token,
                workerid:this.userStore.user.worker_id,
                workername:this.userStore.user.worker_name,
                phone: this.userStore.user.phone,
              } }, '*');
          } else {
            console.warn('iframe not found or contentWindow is null');
          }
        };
      }
    });
    // 接受vue -> uni-app 发来的消息
    window.addEventListener('message', this.handleVueToUniAppMessage);
    // #endif
  },
  methods: {
    handleVueToUniAppMessage (event) {
      // #ifdef H5
      if (event.data?.type === 'vueToUniAppMessage') {
        this.back()
        // alert('收到来自 Vue 的消息：' + event.data.payload);
      }
      // #endif
    },
    // 发送消息
    sendAppInitMessageToWebView () {
      // #ifdef APP-PLUS
      const self = this;
      plus.runtime.getProperty(plus.runtime.appid, function () {
        const jsCode = `handleUniAppMessage({
          type: 'appInit',
          payload: 'app',
          token: '${self.userStore.user.token}',
          workerid: '${self.userStore.user.worker_id}',
          workername: '${self.userStore.user.worker_name}',
            phone: '${self.userStore.user.phone}',
        })`;

        self.wv.evalJS(jsCode);
      });
      // #endif
    },
    // app端 vue 向 uni-app 发送消息
    handleWebViewMessage (e) {
      // #ifdef APP-PLUS
      const data = e.detail.data;
      if (data[0]?.type === 'vueInAppToUniAppMessage') {
        if (data[0]?.message == 'back') {
          this.back()
        } else if (data[0]?.message == 'Switchcolors') {
          this.backgroundColor = '#15a096'
        } else if (data[0]?.message == 'backgroundImage') {
          this.backgroundColor = 'linear-gradient(60deg, #64b3f4 0%, #c2e59c 100%)'
        }else if (data[0]?.message == 'backgroundColor') {
          this.backgroundColor = '#ffffff'
        }

      }
      // #endif
    },
    waitForWebviewChildWithRetry (currentWebview, onSuccess, maxRetries = 10) {
      // #ifdef APP-PLUS
      let retryCount = 0;
      const tryGetChild = () => {
        const children = currentWebview.children();
        if (children && children.length > 0 && children[0]) {
          const wv = children[0];
          onSuccess(wv);
        } else if (retryCount < maxRetries) {
          retryCount++;
          console.log(`重试获取 web-view（第 ${retryCount} 次）`);
          setTimeout(tryGetChild, 100);
        } else {
          console.error(' 获取 web-view 子窗口失败（超出最大重试次数）');
        }
      };

      tryGetChild();
      // #endif
    },
    // 页面销毁前发送消息
    sendMessageToWebViewBeforeDestroy() {
      // #ifdef APP-PLUS
      if (this.wv) {
        const jsCode = `handleUniAppMessage({
      type: 'pageWillDestroy',
      payload: 'Page is about to be destroyed'
    })`;
        this.wv.evalJS(jsCode);
      }
      // #endif

      // #ifdef H5
      const iframe = document.querySelector('iframe');
      if (iframe && iframe.contentWindow) {
        iframe.contentWindow.postMessage({
          type: 'uniAppToVuedestroy',
          payload: 'pageWillDestroy'
        }, '*');
      }
      // #endif
    },
    // 返回
    back () {
      uni.switchTab({
        url: '/pages/workspace/home/index'
      });
    }
  }
}
</script>

<style scoped>
.container {
  position: relative;
  width: 100vw;
  height: 100vh;
  /* background-color: #15a096; */

}
</style>
